<template>
  <div class="home-container">
    <van-button style="position: fixed; right: 0; top: 50%;transform: translate(0, -50%);" icon="plus" type="info"
      @click="addOrder" v-if="self.role === 1" />
    <div class="home-container-top">
      <div class="home-container-top-search">
        <van-search class="home-container-top-search-input" v-model="search.gameName" placeholder="搜索游戏名称" />
      </div>
      <div class="home-container-top-selcet">
        <div class="home-container-top-selcet-list">
          <div class="home-container-top-selcet-list-item" @click="changeGame(0)">
            <img src="@/assets/all.jpg" style="width: 55%;" />
            <span
              :class="search.gameId === 0 ? 'home-container-top-selcet-list-item-text-active' : 'home-container-top-selcet-list-item-text'">全部</span>
          </div>
          <div class="home-container-top-selcet-list-item" v-for="item in gameList" :key="item.id"
            @click="changeGame(item.id)">
            <!-- <div class="home-container-top-selcet-list-item-top"> -->
            <img :src="item.img" style="width: 55%;" />
            <!-- </div> -->
            <span
              :class="search.gameId === item.id ? 'home-container-top-selcet-list-item-text-active' : 'home-container-top-selcet-list-item-text'">{{
                item.gameName }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="home-container-bottom">
      <van-empty v-if="!filter().length" image="search" description="暂无数据" />
      <div v-if="filter().length" class="home-container-bottom-item" v-for="item in filter()" :key="'order-' + item.id">
        <div class="home-container-bottom-item-box">
          <div class="home-container-bottom-item-box-top">
            <div class="home-container-bottom-item-box-top-left">
              <img :src="findGame(item.gameId).img" alt="">
            </div>
            <div class="home-container-bottom-item-box-top-right">
              <div class="home-container-bottom-item-box-top-right-top">
                <span class="home-container-bottom-item-box-top-right-top-gamename"> 订单编号:
                  {{ item.orderNo }}</span>

                <span class="home-container-bottom-item-box-top-right-top-price">{{ `￥${self.role === 2 ?
                  item.dashouyongjin.toFixed(2) : item.price.toFixed(2)}`
                }}</span>
              </div>
              <div class="home-container-bottom-item-box-top-right-bottom">
                <span class="home-container-bottom-item-box-top-right-top-gamename">游戏名称: {{
                  findGame(item.gameId).gameName
                }}</span>
                <div>游戏类型: {{ item.gameType === 1 ? '端游' : '手游' }}</div>
                <div>排位类型: {{ item.playerNum === 1 ? '单排' : '双排' }} {{ '(' + (item.playerId && item.orderStatus === 1 ? 1 : !item.playerId && item.orderStatus === 1 ? 0 : item.playerNum) + '/' + item.playerNum
                  + ')' }}</div>
                  <div v-if="self.role === 1">订单状态: {{ item.orderStatus === 1 ? '待接单' : item.orderStatus === 2 ? '进行中' : item.orderStatus === 3 ? '待审核' : item.orderStatus === 4 ? '已完成' : '已取消'}}</div>
                <div>{{ item.createRemark || '暂无备注' }}</div>
              </div>
            </div>
          </div>
          <div class="home-container-bottom-item-box-bottom">
            <div class="home-container-bottom-item-box-bottom-left">
              <van-icon name="underway-o" />
              <span class="home-container-bottom-item-box-bottom-left-text">{{ `创建时间: ${formatDate(new
                Date(item.createdAt).getTime())}` }}</span>
            </div>
            <div class="home-container-bottom-item-box-bottom-right">
              <van-button type="info" size="small" v-if="self.role === 2" @click="qiangdan(item)">立即抢单</van-button>
              <van-button type="info" size="small" v-if="self.role === 1 && item.orderStatus === 1"
                @click="usercancel(item)">取消订单</van-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import game from '@/plugins/api/game';
import order from '@/plugins/api/order';
import user from '@/plugins/api/user';
import dealApi from '@/plugins/api/deal';
import { fuzzyMatch } from '@/plugins/utils/filterArray';
import { formatTime } from "@/plugins/utils/timeUtils";
import { userCaozuo, updateSelf, orderCaozuo } from '@/plugins/utils/caozuojilu'
export default {
  name: 'HomeView',
  components: {
  },
  data() {
    return {
      gameList: [],
      orders: [],
      search: {
        gameName: '',
        gameId: 0,
        orderStatus: 1
      },
      self: this.$global.self,
      interval: null
    }
  },
  beforeDestroy() {
    if (this.interval) {
      clearInterval(this.interval)
      this.interval = null
      console.log(this.interval, "销毁组件");
    }
  },
  mounted() {
    this.getGameList()
    this.getOrderList()
    this.task()
  },
  methods: {
    async getGameList() {
      const res = await game.list()
      if (res.code === 200) {
        this.gameList = res.data
      }
    },
    formatDate(timestamp) {
      return formatTime(timestamp)
    },
    async getOrderList() {
      const res = await order.list()
      console.log(res);

      if (res.code === 200) {
        this.orders = res.data.filter(item => item.orderStatus !== 9)
      }
    },
    findGame(gameId) {
      return this.gameList.find(item => item.id === gameId)
    },
    addOrder() {
      this.$router.push('/order/modify')
    },
    filter() {
      console.log(this.self);
      if (this.self.role === 2) {
        if (this.search.gameId === 0) {
          const arr = this.orders.filter(item => {
            const arr = item.playerId.split(',')
            const ex = arr.find(items => items === String(this.self.id))
            return !ex && item.orderStatus === 1
          }).reverse()
          arr.sort((a, b) => {
            const numA = Number(a.playerNum) || 0;
            const numB = Number(b.playerNum) || 0;
            return numB - numA;
          })
          console.log(arr);
          return arr
        }
        // console.log(this.search);

        const arr = fuzzyMatch(this.orders, this.search)
        arr.sort((a, b) => {
          const numA = Number(a.playerNum) || 0;
          const numB = Number(b.playerNum) || 0;
          return numB - numA;
        })
        return arr
      }
      if (this.self.role === 1) {
        const obj = {}
        obj.userId = this.self.id
        obj.gameId = this.search.gameId ? this.search.gameId : null
        return fuzzyMatch(this.orders, obj).reverse()
      }
      return []

    },
    async qiangdan(item) {
      const that = this
      console.log(item);
      const o = await order.getById(item)
      if (o.code === 200) {
        const oo = o.data
        console.log(oo);

        if (oo.orderStatus === 1) {
          const parr = oo.playerId ? oo.playerId.split(',') : []
          parr.push(that.self.id)
          oo.playerId = parr.join(',')
          if (oo.playerNum === parr.length) {
            oo.orderStatus = 2
            oo.jiedanTime = new Date().getTime()
          } else {
            oo.orderStatus = 1
          }
          const res = await order.modify(oo)
          if (res.code === 200) {
            await orderCaozuo.update(oo)
            that.getOrderList()
          } else {
            that.$toast.fail(res.msg)
          }
        } else {
          that.$toast.fail('订单已抢走')
        }
      } else {
        that.$toast.fail('订单已抢走')
      }
    },

    async usercancel(item) {
      const that = this
      console.log(item);
      const o = await order.getById(item)
      if (o.code === 200) {
        const oo = o.data
        if (oo.orderStatus === 1 && !oo.playerId) {
          oo.orderStatus = 0
          that.self.balance = Number(that.self.balance) + Number(oo.price)
          const res = await order.modify(oo)
          if (res.code === 200) {
            const dealObj = {
              userId: that.self.id,
              value: `${Number(oo.price)}`,
              type: 1,
              createTime: new Date().getTime(),
              orderNo: item.orderNo
            }
            const userRes = await user.update(that.self)
            if (userRes.code === 200) {
              await dealApi.modify(dealObj)
              await updateSelf(userRes.data)
              await orderCaozuo.update(oo)
              that.$toast.success('取消订单成功')
              that.getOrderList()
            }
          } else {
            that.$toast.fail(res.msg)
          }
        } else {
          that.$toast.fail(o.msg)
        }
      } else {
        that.$toast.fail(o.msg)
      }
    },

    changeGame(id) {
      this.search.gameId = id
    },
    task() {
      const that = this
      if (that.interval) {
        clearInterval(that.interval)
      }
      that.interval = setInterval(() => {
        that.getOrderList()
      }, 2000);
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/global/mixin.scss';

.home-container {
  width: 100%;
  height: 100%;

  &-top {
    background-color: #fff;

    &-search {
      @include flex(row, flex-start, center);
      width: 100%;

      &-input {
        width: 100%;
      }
    }

    &-selcet {
      width: 100%;

      &-list {
        padding: 5px 10px;
        @include flex(row, flex-start, center);
        overflow-x: auto;

        &-item {
          flex: 0 0 20%;
          height: 58px;
          // background-color: red;
          @include flex(column, space-between, center);
          flex-wrap: nowrap;

          &-text,
          &-text-active {
            font-size: 12px;
            color: #ccc;
          }

          &-text-active {
            color: #1989fa;
          }
        }
      }
    }
  }

  &-bottom {
    padding: 0 10px;

    &-item {
      width: 100%;
      background-color: #fff;
      margin-top: 10px;
      border-radius: 8px;

      &-box {
        padding-top: 10px;
        padding-left: 10px;
        padding-right: 20px;
        padding-bottom: 10px;

        &-top {
          width: 100%;
          @include flex(row, flex-start, center);

          &-left {
            flex: 0 0 60px;

            img {
              width: 100%;
            }
          }

          &-right {
            flex: 1;
            @include flex(column, center, flex-start);

            &-top {
              width: 100%;
              font-size: 14px;
              font-weight: 600;
              @include flex(row, space-between, center);

              &-price {
                color: red;
              }
            }

            &-bottom {
              font-size: 12px;
              color: #ccc;
              margin-top: 5px;
            }
          }
        }

        &-bottom {
          padding-left: 10px;
          margin-top: 5px;
          font-size: 12px;
          color: #999;
          @include flex(row, space-between, center);

          &-left-text {
            margin-left: 5px;
          }
        }
      }
    }
  }
}
</style>